package net.entelijan.cobean.worker;

import java.lang.reflect.Method;

/**
 * The name method finder looks in a bean for methods beginning with 'do' for
 * the do method and 'validate' for the validate method. The rest of the method
 * is defined by the member 'name'
 * 
 * E.g. if name is 'import' methods 'validateImport' with no parameter would
 * match for the validate method and 'doImport' with no parameter or
 * ITaskCompanion as a single parameter would match.
 * 
 */
public class NameMethodFinder implements IMethodFinder {

	private String name;

	public NameMethodFinder() {
		super();
	}

	public NameMethodFinder(String name) {
		super();
		this.name = name;
	}

	@Override
	public Method findDoMethod(Object bean) {
		Method re = null;
		String mName = createPrefixMethodName("do", this.name);
		for (Method m : bean.getClass().getMethods()) {
			if (m.getName().equals(mName)) {
				re = m;
			}
		}
		return re;
	}

	@Override
	public Method findValidationMethod(Object bean) {
		Method re = null;
		String mName = createPrefixMethodName("validate", this.name);
		for (Method m : bean.getClass().getMethods()) {
			if (m.getName().equals(mName)) {
				re = m;
			}
		}
		return re;
	}

	private String createPrefixMethodName(String prefix, String name) {
		String re;
		if (startsWithLowercase(name)) {
			re = prefix + firstToUppercase(name);
		} else {
			re = prefix + name;
		}
		return re;
	}

	private boolean startsWithLowercase(String name) {
		boolean re = false;
		if (name != null && name.length() > 0
				&& Character.isLowerCase(name.charAt(0))) {
			re = true;
		}
		return re;
	}

	private String firstToUppercase(String name) {
		return Character.toUpperCase(name.charAt(0)) + name.substring(1);
	}

	@Override
	public String toString() {
		return getClass().getName() + " " + this.name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
